package com.mexico.inloancash.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.activity.IndiaCerActivity;
import com.mexico.inloancash.activity.IndiaLoginActivity;
import com.mexico.inloancash.bean.IddDataOCRInfo;
import com.mexico.inloancash.bean.PcDataBean;
import com.mexico.inloancash.utils.DeviceIdUtil;
import com.mexico.inloancash.utils.FileUtils;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UploadManager;
import com.mexico.inloancash.R;
import com.mexico.inloancash.bean.BaseBean;
import com.mexico.inloancash.bean.India_File_ListBean;
import com.mexico.inloancash.bean.India_PostFace_ComparisonListBean;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.india_interfacedai.IndiaDealDialogInterface;
import com.mexico.inloancash.utils.Auth;
import com.mexico.inloancash.utils.MyToast;
import com.mexico.inloancash.utils.MyUtils;
import com.mexico.inloancash.utils.permission.RxPermissions;
import com.mexico.inloancash.utils.permission.SchedulerTransformer;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;

import ai.advance.liveness.lib.LivenessResult;
import ai.advance.liveness.sdk.activity.LivenessActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;

import static android.app.Activity.RESULT_OK;

/**
 * 人脸识别页面
 */
public class IndiaStepOneAuthFragment extends BaseFragment implements IndiaDealDialogInterface {

    //pan 卡
    @BindView(R.id.iv_pan_card)
    ImageView mImageViewPanCard;

    //活体检测
    @BindView(R.id.iv_take_self)
    ImageView idTakeSelf;

    @BindView(R.id.bt_commit)
    Button btCommit;

    private View one;
    Unbinder unbinder;
    private IndiaCerActivity   activity;//用于修改对应标题

    private UploadManager uploadManager;
    private Recorder recorder;
    private KeyGenerator keyGen;
    Configuration config;
    private String upToken;

    String accessKey = "kFiJToSdmLlsn2ttg-L8_X51Cu4oFialS-9qIKtB";
    String secretKey = "MGYWxZcIKcDcxzxJfDiar42ERXg1Wtimz-ixCl0U";
    String bucket = "ynimage001";

    public static final int REQUEST_CODE_LIVENESS = 1000; //人脸活体检测 照片
    public static final int REQUEST_CODE_PAN_CARD = 1003;//PAN卡 照片

    private String panOcrInfo = "";//pan卡ocr的识别信息
    private String idCardFrontInfo = "";//身份证正面ocr的识别信息
    private String idCardBackInfo = "";//身份证反面ocr的识别信息
    private String faceContrastInfo = "";//人脸比对的信息

    private String panCardKey = "";//上传到七牛云的 pan卡地址
    private String selfKey = "";//上传到七牛云的 自己的正面照卡地址
    private String idCardFrontKey = "";//上传到七牛云的 身份证正面照卡地址
    private String idCardBackKey = "";//上传到七牛云的 身份证反面照片卡地址

    private File panFile;//压缩后的pan文件
    private File takeSelfFile;//人脸活体检测的文件

    private String idCard = "", username = "", panCardNum = "";

    /**
     * 调起拍照
     */
    private File currentImageFile;
    Uri uri;

    public IndiaStepOneAuthFragment(IndiaCerActivity   activity) {
        this.activity = activity;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        one = inflater.inflate(R.layout.india_activity_one_view_auth_layout_fragment, container, false);
        unbinder = ButterKnife.bind(this, one);
        activity.mIndiaUpdateTitle(getString(R.string.step1_title));
        config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .recorder(null)           // recorder分片上传时，已上传片记录器。默认null
                .recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zoneAs0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        Auth  tackleAuth = Auth .create(accessKey, secretKey);
        upToken = tackleAuth.uploadToken(bucket);
        return one;
    }

    @OnClick({ R.id.iv_take_self, R.id.bt_commit, R.id.iv_pan_card})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_pan_card:
                //pan卡
                chIDCard(REQUEST_CODE_PAN_CARD);
                break;
            case R.id.iv_take_self:
                new RxPermissions(activity)
                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA)
                        .compose(new SchedulerTransformer<Boolean>())
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                toJump();
                            } else {
                                MyToast.show(activity, getString(R.string.permission));
                            }
                        });
                break;
            case R.id.bt_commit:
                //Pan 卡信息有误，请重新拍照上传
                if (TextUtils.isEmpty(panOcrInfo)) {
                    Toast.makeText(getContext(), getString(R.string.pan_card_error), Toast.LENGTH_LONG).show();
                    return;
                }

                //请重新拍摄自己的正面照片和身份证正面照片
                if (TextUtils.isEmpty(faceContrastInfo)) {
                    Toast.makeText(getContext(), getString(R.string.self_id_card_error), Toast.LENGTH_LONG).show();
                    return;
                }

                //请重新拍摄自己的身份证正面照片
                if (TextUtils.isEmpty(idCardFrontInfo)) {
                    Toast.makeText(getContext(), getString(R.string.id_card_error), Toast.LENGTH_LONG).show();
                    return;
                }

                //请重新拍摄自己的身份证正面照片
                if (TextUtils.isEmpty(idCardBackInfo)) {
                    Toast.makeText(getContext(), getString(R.string.id_card_back_error), Toast.LENGTH_LONG).show();
                    return;
                }

                //private File idCardFrontFile;//压缩后的身份证正面文件
                //private File idCardBackFile;//压缩后的身份证反面文件
                //private File panFile;//压缩后的pan文件
                //private File takeSelfFile;//人脸活体检测的文件

                //Pan 卡信息有误，请重新拍照上传
                if (panFile == null) {
                    Toast.makeText(getContext(), getString(R.string.pan_card_error), Toast.LENGTH_LONG).show();
                    return;
                }

                //请拍摄自己的正面清晰照片
                if (takeSelfFile == null) {
                    Toast.makeText(getContext(), getString(R.string.take_self_photo), Toast.LENGTH_LONG).show();
                    return;
                }

                //<!--请重新拍摄自己的身份证正面照片-->
                if (TextUtils.isEmpty(idCard) || TextUtils.isEmpty(username)) {
                    Toast.makeText(getContext(), getString(R.string.id_card_error), Toast.LENGTH_LONG).show();
                    return;
                }

                if (TextUtils.isEmpty(panCardNum)) {
                    Toast.makeText(getContext(), getString(R.string.pan_card_error), Toast.LENGTH_LONG).show();
                    return;
                }

                loading.show();
                //上传照片到七牛云 然后再上传到自己的服务器
                if (null != panFile && null != takeSelfFile) {
                    for (int i = 0; i < 4; i++) {
                        String token = upToken;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        String key1 = "icon_" + i + sdf.format(new Date());
                        uploadManager = new UploadManager(config);
                        File myFile;
                        if (i == 0) {
                            myFile = panFile;//pan卡
                        } else{
                            myFile = takeSelfFile;//自己的正面照片
                        }
                        int finalI = i;

                        //private String panCardKey="";//上传到七牛云的 pan卡地址
                        //private String selfKey="";//上传到七牛云的 自己的正面照卡地址
                        //private String idCardFrontKey="";//上传到七牛云的 身份证正面照卡地址
                        // private String idCardBackKey="";//上传到七牛云的 身份证反面照片卡地址

                        uploadManager.put(myFile, key1, token,
                                (key, info, res) -> {
                                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                                    if (info.isOK()) {
                                        if (finalI == 0) {
                                            //pan卡
                                            panCardKey = key;
                                            Log.e("data", "panCardKey:" + panCardKey);
                                        } else if (finalI == 1) {
                                            //自己的正面照片
                                            selfKey = key;
                                            Log.e("data", "selfKey:" + selfKey);
                                        } else if (finalI == 2) {
                                            //身份证正面照片
                                            idCardFrontKey = key;
                                            Log.e("data", "idCardFrontKey:" + idCardFrontKey);
                                        } else if (finalI == 3) {
                                            //身份证反面照片
                                            idCardBackKey = key;
                                            Log.e("data", "idCardBackKey:" + idCardBackKey);
                                        }
                                        //如果4张照片 都上传成功后 就上传后台
                                        if (!TextUtils.isEmpty(panCardKey) && !TextUtils.isEmpty(selfKey) && !TextUtils.isEmpty(idCardFrontKey) && !TextUtils.isEmpty(idCardBackKey)) {
                                            UploadInfo();
                                            Log.e("data", "Uploaded backend");
                                        }
                                    } else {
                                        loading.dismiss();
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(getContext(), "Image upload failed, please check network connection", Toast.LENGTH_SHORT).show();
                                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                            }
                                        });
                                    }
                                }, null);
                    }
                }
                break;
        }
    }


    /**
     * 选择照片 身份证照片 PAN 照片
     */
    @SuppressLint("CheckResult")
    private void chIDCard(int REQUEST_CODE) {
        Log.d("loan", "chooseIDCard");
        new RxPermissions(getActivity())
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Matisse.from(this)
                                .choose(EnumSet.of(MimeType.JPEG, MimeType.PNG))
                                .showSingleMediaType(true)
                                .maxSelectable(1)
                                .maxOriginalSize(10)
                                .countable(false)
                                //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                                .capture(true)
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//强制让照片选择页面竖屏显示 横屏拍照会有bug
                                .captureStrategy(new CaptureStrategy(true, "com.indiarapido.indiapeso.fileProvider"))
                                .thumbnailScale(0.85f)
                                .showPreview(false)
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//强制让照片选择页面竖屏显示 横屏拍照会有bug
                                .imageEngine(new GlideEngine())
                                .theme(R.style.MyMatisse)
                                .forResult(REQUEST_CODE);
                    }
                });
    }

    /**
     * 压缩身份证  并且进行 ocr 识别
     *
     * @param uri
     */
    public void comIDCard(Uri uri, int requestCode) {
        Log.d("loan", "compressIDCard");
        String filePath = FileUtils.getRealFilePath(getContext(), uri);
        if (TextUtils.isEmpty(filePath)) {
            loading.dismiss();
            Toast.makeText(getActivity(), "path error", Toast.LENGTH_SHORT).show();
            return;
        }
        List<String> photos = new ArrayList<>();
        photos.add(filePath);
        Flowable.just(photos)
                .observeOn(Schedulers.io())
                .map(new Function<List<String>, List<File>>() {
                    @Override
                    public List<File> apply(@NonNull List<String> list) throws Exception {
                        // 同步方法直接返回压缩后的文件
                        if (list.size() > 0) {
                            String path = Luban.with(getActivity()).load(list).get().get(0).getAbsolutePath();
                            File file = new File(path);
//                            switch (requestCode) {
//                                case REQUEST_CODE_ID_CARD_FRONT:
//                                    idCardFrontFile = file;
//                                    break;
//                                case REQUEST_CODE_ID_CARD_BACK:
//                                    idCardBackFile = file;
//                                    break;
//                                case REQUEST_CODE_PAN_CARD:
//                                    panFile = file;
//                                    break;
//                            }
                            ManFile(file, requestCode);
                        } else {
                            loading.dismiss();
                        }
                        return Luban.with(getActivity()).load(list).get();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
    }

    @Nullable
    private Uri saveTheBitmap(@NonNull final Context context,
                              @NonNull final Bitmap bitmap,
                              @NonNull final Bitmap.CompressFormat format,
                              @NonNull final String mimeType,
                              @NonNull final String displayName) throws IOException {
        String relativeLocation = "Pictures/DomepetCash";
        final ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);
        final ContentResolver resolver = context.getContentResolver();
        OutputStream stream = null;
        Uri uri = null;

        try {
            final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            uri = resolver.insert(contentUri, contentValues);
            if (uri == null) {
                throw new IOException("Failed to create new MediaStore record.");
            }
            stream = resolver.openOutputStream(uri);
            if (stream == null) {
                throw new IOException("Failed to get output stream.");
            }
            if (bitmap.compress(format, 95, stream) == false) {
                throw new IOException("Failed to save bitmap.");
            }
        } catch (IOException e) {
            if (uri != null) {
                // Don't leave an orphan entry in the MediaStore
                resolver.delete(uri, null, null);
            }
            throw e;
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
        return uri;
    }


    public static File bitToFile(Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
        Log.d("loan", "bitmapToFile:" + fileNameToSave);
        //create a file to write bitmap data
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
            file.createNewFile();

            //Convert bitmap to byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos); // YOU can also save it in JPEG
            byte[] bitmapdata = bos.toByteArray();

            //write the bytes in file
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return file; // it will return null
        }
    }


    /**
     * 保存认证的照片信息
     */
    public void UploadInfo() {
        IndiaRequestApi   api = IndiaDKFactory.getInstance().getApi();
        retrofit2.Call<String> saveInfo = api.holdInfo(
                MyPreferencesManager.getString("token", ""),
                MyApplication.source,
                username,//姓名
                idCard,//身份证号

                idCardFrontKey,//身份证正面
                idCardBackKey,//身份证反面
                selfKey,//人脸自拍照片
                panCardKey,//pan卡照片

                faceContrastInfo,//人脸比对信息
                idCardFrontInfo,//身份证正面信息
                idCardBackInfo,//身份证反面信息
                panOcrInfo,//pan卡信息
                panCardNum,//pan卡上面的卡号
                MyPreferencesManager.getAppsFlyerTrackerName()//AppsFlyer 归因
        );

        saveInfo.enqueue(new Callback<String>() {
            @Override
            public void onResponse(retrofit2.Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    BaseBean  baseMomBean = new Gson().fromJson(response.body(), BaseBean .class);
                    if (baseMomBean.getCode() == 200) {
                        activity.mIndiaSetTrop(1);
                        //身份认证成功 adjust统计
                        //AdjustHelper.AuthenticationSuccessful();

                    } else if (baseMomBean.getCode() == 401) {
                        Intent intent = new Intent(getContext(), IndiaLoginActivity.class);
                        startActivity(intent);
                    } else {
                        MyToast.show(getContext(), baseMomBean.getMsg());
                    }
                }
                loading.dismiss();
            }

            @Override
            public void onFailure(retrofit2.Call<String> call, Throwable t) {
                loading.dismiss();
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    private void toJump() {
        Intent intent = new Intent(getActivity(), LivenessActivity.class);
        startActivityForResult(intent, REQUEST_CODE_LIVENESS);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 1://文件中选择照片 没有使用了
                break;
            case 2://拍照完成回调 没有使用了
                break;
            case REQUEST_CODE_LIVENESS:
                //人脸检查识别返回
                if (resultCode == RESULT_OK) {
                    Log.d("onActivityResult", "onActivityResult:" + REQUEST_CODE_LIVENESS);
                    if (LivenessResult.isSuccess()) {
                        Bitmap livenessBitmap = LivenessResult.getLivenessBitmap();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            try {
                                Uri uri = null;
                                uri = saveTheBitmap(getContext(), livenessBitmap, Bitmap.CompressFormat.JPEG, "image/jpeg", System.currentTimeMillis() / 1000 + ".jpeg");
                                if (uri != null) {
                                    String path = FileUtils.getRealFilePath(getContext(), uri);
                                    Log.d("loan", "saveImage:" + path);
                                    takeSelfFile = new File(path);
                                    Log.d("loan", "Liveness file exists:" + takeSelfFile.exists());
                                    Glide.with(getContext()).load(livenessBitmap).into(idTakeSelf);
                                    FeComparison();
                                } else {
                                    Log.d("loan", "uri is null");
                                    MyToast.show(getContext(), "uri is null");
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                MyToast.show(getContext(), "save failed");
                            }
                        } else {
                            takeSelfFile = bitToFile(livenessBitmap, System.currentTimeMillis() / 1000 + ".jpeg");
                            Glide.with(getContext()).load(livenessBitmap).into(idTakeSelf);
                            FeComparison();
                        }
                    } else {
                        Log.d("loan", getString(R.string.face_failed));
                    }
                }
                break;
            case REQUEST_CODE_PAN_CARD://pan 卡
                Log.e("data", "onActivityResult:" + REQUEST_CODE_PAN_CARD);
                if (resultCode == RESULT_OK) {
                    List<Uri> results = Matisse.obtainResult(data);
                    if (results != null && !results.isEmpty()) {
                        Glide.with(getContext()).load(results.get(0)).into(mImageViewPanCard);
                        //压缩照片
                        comIDCard(results.get(0), REQUEST_CODE_PAN_CARD);
                        loading.show();
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 对比两个手持照片和活检
     */
    public void FeComparison() {
        if (takeSelfFile == null) {
            return;
        }
        loading.show();
        OkHttpUtils
                .post()
                .url("https://in-api.advance.ai/in/openapi/face-identity/v1/face-comparison")
                .addFile("secondImage", takeSelfFile.getName(), takeSelfFile)
                .addHeader("X-ADVAI-KEY", MyApplication.INDIAKEY)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show(getActivity(), e.getMessage());
                        loading.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        loading.dismiss();
                        //人脸比对信息
                        faceContrastInfo = response;
                    }
                });
    }


    /**
     * 拍照
     */
    @SuppressLint("CheckResult")
    @Override
    public void doPlay() {
        new RxPermissions(activity)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .compose(new SchedulerTransformer<Boolean>())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        startCamera();
                    } else {
                        MyToast.show(getContext(), getString(R.string.permission));
                    }
                });
    }

    /**
     * 打开图片选择器
     */
    @SuppressLint("CheckResult")
    @Override
    public void choose() {
        new RxPermissions(activity)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .compose(new SchedulerTransformer<Boolean>())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 1);
                    } else {
                        MyToast.show(getContext(), getString(R.string.permission));
                    }
                });
    }


    /**
     * 印度的身份证  pan卡 OCR 识别
     *
     * @param file
     */
    public void ManFile(File file, int requestCode) {
        //public static final int REQUEST_CODE_ID_CARD_FRONT = 1001;//身份证正面照片
        //public static final int REQUEST_CODE_ID_CARD_BACK = 1002;//身份证背面照片
        //public static final int REQUEST_CODE_PAN_CARD = 1003;//PAN卡 照片
        String cardType = "";
        switch (requestCode) {
            case REQUEST_CODE_PAN_CARD:
                cardType = "PAN_FRONT";
                break;
        }
        OkHttpUtils
                .post()
                .url("https://in-api.advance.ai/in/openapi/face-identity/v1/id-card-ocr")
                .addFile("image", file.getName(), file)
                .addHeader("X-ADVAI-KEY", MyApplication.INDIAKEY)//ocr 对应 印度的key
                .addParams("cardType", cardType)//cardType 类型  cardType 应该是 AADHAAR_FRONT 或 AADHAAR_BACK、PAN_FRONT
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        loading.dismiss();
                        MyToast.show(getActivity(), e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        switch (requestCode) {
                            case REQUEST_CODE_PAN_CARD:
                                Log.e("data","REQUEST_CODE_PAN_CARD"+response);
                                loading.dismiss();
                                //pan卡识别信息
                                panOcrInfo = response;
                                PcDataBean pcDataBean = new Gson().fromJson(response, PcDataBean.class);
                                //获取pan卡号
                                if(null!=pcDataBean.getData()){
                                    panCardNum = pcDataBean.getData().getValues().getIdNumber();
                                }
                                //Log.e("data", "====REQUEST_CODE_PAN_CARD====onResponse" + response.toString());
                                break;
                        }
                    }
                });
    }

    /**
     * 调取拍照
     */
    public void startCamera() {
        File dir = new File(Environment.getExternalStorageDirectory(), "myimage");//在sd下创建文件夹myimage；Environment.getExternalStorageDirectory()得到SD卡路径文件
        if (!dir.exists()) {    //exists()判断文件是否存在，不存在则创建文件
            dir.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式在android中，创建文件时，文件名中不能包含“：”冒号
        String filename = df.format(new Date());
        currentImageFile = new File(dir, filename + ".jpg");
        if (!currentImageFile.exists()) {
            try {
                currentImageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT < 24) {
            currentImageFile = new File(dir, filename + ".jpg");
            // 从文件中创建uri
            uri = Uri.fromFile(currentImageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            // 兼容Android 7.0 使用共享文件的形式
            ContentValues contentValues = new ContentValues();
            uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        startActivityForResult(intent, 2);
    }
}
